//
//  SRMe+Cate.m
//  SportRing
//
//  Created by Apple on 14/10/27.
//  Copyright (c) 2014年 HotOne. All rights reserved.
//

#import "SRMe+Cate.h"
#import "SRDB.h"
#import <CoreData+MagicalRecord.h>

static SRMe * currentUserInstance = nil;

@implementation SRMe (Cate)

+ (void)setCurrentUser:(SRMe *)user
{
    currentUserInstance = user;
}

+ (SRMe *)currentUser
{
    return currentUserInstance;
}

+ (SRMe *)userWithName:(NSString *)name password:(NSString *)password
{
    __block SRMe * user = nil;
    [MagicalRecord saveUsingCurrentThreadContextWithBlockAndWait:^(NSManagedObjectContext *localContext)
     {
         user = [SRMe MR_createEntity];
         user.userName = name;
         user.userPwd = password;
         user.birthday = @"";
         user.gender = @(1);
         user.headPhoto = @"";
         user.lastModifyDate = @"";
         user.nickName = @"";
         user.weight = @(0);
         user.height = @(0);
     }];
    return user;
}

- (void)configAttributesWithBlock:(void(^)(SRMe * userSelf))block
{
    [MagicalRecord saveUsingCurrentThreadContextWithBlockAndWait:^(NSManagedObjectContext *localContext){
        block(self);
    }];
}

- (void)setAvatarUrl:(NSString *)url
{
    self.headPhoto = [NSString stringWithFormat:@"http://114.215.127.64:8089/assets/upload/headphoto/%@", url];
}

@end


@implementation SRMe (Find)

+ (SRMe *)findUserByName:(NSString *)name
{
    return [SRMe MR_findFirstByAttribute:@"userName" withValue:name];
}

+ (SRMe *)findUserAndCreateIfNotExistByName:(NSString *)name
{
    SRMe * user = [SRMe findUserByName:name];
    if (user == nil)
    {
        user = [SRMe userWithName:name password:nil];
    }
    return user;
}

- (CGFloat)allDistance
{
    __block float all = 0;
    NSArray * months = [SRMonth findAllMonthsForMe:[SRMe currentUser]];
    [months enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        SRMonth * month = obj;
        all += [month countOfDistance];
    }];
    return all;
}

- (NSInteger)allSteps
{
    __block float all = 0;
    NSArray * months = [SRMonth findAllMonthsForMe:[SRMe currentUser]];
    [months enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        SRMonth * month = obj;
        all += [month countOfSteps];
    }];
    return all;
}

- (CGFloat)allCalorie
{
    __block float all = 0;
    NSArray * months = [SRMonth findAllMonthsForMe:[SRMe currentUser]];
    [months enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        SRMonth * month = obj;
        all += [month countOfCalorie];
    }];
    return all;
}

@end